﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using System.ComponentModel;
using GiveAQuiz.QuizManager.ViewModel;
using System.Windows.Browser;
using GiveAQuiz.Common.Mvvm;

namespace GiveAQuiz.QuizManager
{
  public partial class QuizTaker : UserControl
  {
    public QuizTaker()
    {
      InitializeComponent();

      Loaded += new RoutedEventHandler(QuizTaker_Loaded);
      AppMessages.ShowDialog.Register(this, container =>
        {
          // When someone shows a dialog, handle the closed event and 
          // show the dialog
          container.Item1.Closed += (s, e) => container.Item2();
          container.Item1.Show();
        });
      AppMessages.ShowMessageAndRedirect.Register(this, container =>
        {
          MessageBox.Show(container.Item1, "GiveAQuiz.com", MessageBoxButton.OK);
          HtmlPage.Window.Navigate(container.Item2);
        });

      this.AddHandler(UIElement.KeyUpEvent, new KeyEventHandler(QuizTaker_KeyDown), true);

    }

    // If a number key is selected, attempt to select that answer if it exists
    void QuizTaker_KeyDown(object sender, KeyEventArgs args)
    {
      if (args.Key >= Key.D1 && args.Key <= Key.D9)
      {
        var itemNumber = (int)args.Key - (int)Key.D1;
        CommandHelper.ExecuteCommandOnProperty(DataContext, "CurrentQuestion", "PickAnswerCommand", itemNumber);
      }
      else if (args.Key == Key.Enter)
      {
        CommandHelper.ExecuteCommand(DataContext, "NextQuestionCommand");
      }
    }

    void QuizTaker_Loaded(object sender, RoutedEventArgs e)
    {
      // Set the ViewModel to our data context directly
      // We are using resolution so the dependency chain is set up for us
      DataContext = ViewModel;
    }

    [Import("QuizTakerViewModel")]
    public object ViewModel
    {
      get;
      set;
    }

  }
}
